import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:stacked/stacked.dart';
import 'package:stacked_services/stacked_services.dart';
import 'package:vista/app/di/injection.dart';
import 'package:vista/features/community/viewmodels/image_detail_viewmodel.dart';
import 'package:vista/shared/constants/color.dart';
import 'package:vista/shared/utils/widget_extension.dart';
import 'package:vista/shared/widgets/auth_gate_modal.dart';

/// 图片详情页面
class ImageDetailView extends StatefulWidget {
  final String postId;

  const ImageDetailView({super.key, required this.postId});

  @override
  State<ImageDetailView> createState() => _ImageDetailViewState();
}

class _ImageDetailViewState extends State<ImageDetailView> {
  PageController? _pageController;

  @override
  void initState() {
    super.initState();
    _pageController = PageController();
  }

  @override
  void dispose() {
    _pageController?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return ViewModelBuilder<ImageDetailViewModel>.reactive(
      viewModelBuilder:
          () =>
              ImageDetailViewModel(getIt.get(), getIt.get(), widget.postId)
                ..initialize(),
      builder: (context, model, child) {
        if (model.isBusy || model.post == null) {
          return Scaffold(
            body: Container(
              decoration: const BoxDecoration(color: Colors.black),
              child: const Center(child: CircularProgressIndicator()),
            ),
          );
        }

        return Scaffold(
          backgroundColor: Colors.black,
          body: SizedBox.expand(
            child: Stack(
              children: [
                // 图片背景
                _buildImageBackground(context, model),
                // 左上角返回按钮
                _buildBackButton(context),
                // 底部详情文字
                _buildBottomContent(context, model),
                // 小图索引
                _buildThumbnailIndex(context, model),
              ],
            ),
          ),
        );
      },
    );
  }

  /// 构建图片背景
  Widget _buildImageBackground(
    BuildContext context,
    ImageDetailViewModel model,
  ) {
    final post = model.post!;

    return PageView.builder(
      controller: _pageController,
      onPageChanged: (index) {
        model.setImageIndex(index);
      },
      itemCount: post.images.length,
      itemBuilder: (context, index) {
        return Image.asset(
          post.images[index],
          width: double.infinity,
          height: double.infinity,
          fit: BoxFit.cover,
        );
      },
    );
  }

  /// 构建返回按钮
  Widget _buildBackButton(BuildContext context) {
    return Positioned(
      top: 0,
      left: 0,
      child: SafeArea(
        child: Padding(
          padding: EdgeInsets.all(14.w),
          child: GestureDetector(
            onTap: () => getIt.get<NavigationService>().back(),
            child: Container(
              padding: EdgeInsets.all(8.w),
              decoration: BoxDecoration(
                color: Colors.black.withOpacity(0.3),
                shape: BoxShape.circle,
              ),
              child: Image.asset(
                'assets/images/back.png',
                width: 20.w,
                height: 20.w,
                color: Colors.white,
              ),
            ),
          ),
        ),
      ),
    );
  }

  /// 构建底部内容
  Widget _buildBottomContent(BuildContext context, ImageDetailViewModel model) {
    final post = model.post!;
    final author = model.author;

    return Positioned(
      bottom: 0,
      left: 0,
      right: 0,
      child: Container(
        padding: EdgeInsets.all(20.w),
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [Colors.transparent, Colors.black.withOpacity(0.8)],
          ),
        ),
        child: [
          // 发布者信息
          if (author != null)
            Row(
              children: [
                CircleAvatar(
                  radius: 20.r,
                  backgroundColor: ColorConstants.primaryColor,
                  backgroundImage:
                      author.avatar != null ? AssetImage(author.avatar!) : null,
                  child:
                      author.avatar == null
                          ? Icon(Icons.person, size: 20.w, color: Colors.white)
                          : null,
                ),
                SizedBox(width: 12.w),
                Expanded(
                  child: [
                    Text(
                      author.username,
                      style: TextStyle(
                        fontSize: 16.sp,
                        fontWeight: FontWeight.w700,
                        fontFamily:
                            GoogleFonts.alegreyaSans(
                              fontWeight: FontWeight.w700,
                            ).fontFamily,
                        color: Colors.white,
                      ),
                    ),
                    if (author.signature != null) ...[
                      SizedBox(height: 4.h),
                      Text(
                        author.signature!,
                        style: TextStyle(
                          fontSize: 14.sp,
                          fontFamily:
                              GoogleFonts.alegreyaSans(
                                fontWeight: FontWeight.w400,
                              ).fontFamily,
                          color: Colors.white.withOpacity(0.8),
                        ),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ],
                  ].verticalShot(crossAxisAlignment: CrossAxisAlignment.start),
                ),
                SizedBox(width: 12.w),
                // 点赞按钮
                GestureDetector(
                  onTap: () async {
                    if (model.currentUser == null) {
                      final result = await showDialog<bool>(
                        context: context,
                        builder: (context) => const AuthGateModal(),
                      );
                      if (result == true && context.mounted) {
                        await Navigator.of(context).pushNamed('/login');
                        if (context.mounted) {
                          await model.refreshAuthAndLikeStatus();
                        }
                      }
                      return;
                    }
                    await model.toggleLike();
                  },
                  child: Container(
                    padding: EdgeInsets.all(2.w),
                    decoration: BoxDecoration(
                      color: Colors.black.withOpacity(0),
                      shape: BoxShape.circle,
                    ),
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Icon(
                          model.isLiked
                              ? Icons.favorite
                              : Icons.favorite_border,
                          size: 26.w,
                          color: model.isLiked ? Colors.red : Colors.white,
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          if (author != null) SizedBox(height: 12.h),
          // 动态详情文字
          Text(
            post.content,
            style: TextStyle(
              fontSize: 16.sp,
              fontWeight: FontWeight.w400,
              fontFamily:
                  GoogleFonts.alegreyaSans(
                    fontWeight: FontWeight.w400,
                  ).fontFamily,
              color: Colors.white,
              height: 1.5,
            ),
          ),
        ].verticalShot(crossAxisAlignment: CrossAxisAlignment.start),
      ),
    );
  }

  /// 构建小图索引
  Widget _buildThumbnailIndex(
    BuildContext context,
    ImageDetailViewModel model,
  ) {
    final post = model.post!;

    return Positioned(
      bottom: 160.h,
      left: 0,
      right: 0,
      child: Container(
        height: 60.w,
        padding: EdgeInsets.symmetric(horizontal: 20.w),
        child: ListView.builder(
          scrollDirection: Axis.horizontal,
          itemCount: post.images.length,
          itemBuilder: (context, index) {
            final isSelected = index == model.currentImageIndex;
            return GestureDetector(
              onTap: () {
                _pageController?.animateToPage(
                  index,
                  duration: const Duration(milliseconds: 300),
                  curve: Curves.easeInOut,
                );
              },
              child: Container(
                width: isSelected ? 50.w : 50.w,
                height: isSelected ? 50.w : 50.w,
                margin: EdgeInsets.only(right: 8.w),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(6.r),
                  border: Border.all(
                    color:
                        isSelected
                            ? Colors.white
                            : Colors.white.withOpacity(0.5),
                    width: isSelected ? 2.w : 1.w,
                  ),
                  boxShadow:
                      isSelected
                          ? [
                            BoxShadow(
                              color: Colors.white.withOpacity(0.5),
                              blurRadius: 8,
                              spreadRadius: 2,
                            ),
                          ]
                          : null,
                ),
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(5.r),
                  child: Image.asset(
                    post.images[index],
                    width: double.infinity,
                    height: double.infinity,
                    fit: BoxFit.cover,
                  ),
                ),
              ),
            );
          },
        ),
      ),
    );
  }
}
